﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Drawing;
using System.Web.SessionState;
using Maticsoft.Common;
using System.Text;

namespace MidSoft.Finance.Contract
{
    public partial class Add : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputButton btnCancel;
        public string adminname = "管理部门";
        ChinaSoft.BLL.BLL_tb_MidSoft_Contract bll = new ChinaSoft.BLL.BLL_tb_MidSoft_Contract();

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                 //imgBtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗？\")");
                 BindData();
                 if (Request.Params["ProjectId"] != null && Request.Params["ProjectId"].Trim() != "")
                 {
                     int ProjectInfoId = ChinaSoft.Common.Input.SetInt(Request.Params["ProjectId"]);

                     BindProjectNameData(ProjectInfoId);
                     ClearInfo();
                 }
                 if (Request.Params["ContractID"] != null && Request.Params["ContractID"].Trim() != "")//修改
                 {
                     int ContractId = ChinaSoft.Common.Input.SetInt(Request.Params["ContractID"]);
                     BindContractInfoData(ContractId);
                 }
            }
        }

        private void ClearInfo()
        {
            this.txtContractNumber.Text = string.Empty;
            this.txtContractNumber.Text = string.Empty;
            this.txtContractName.Text = string.Empty;
            this.txtUnit.Text = string.Empty;
            this.txtContractMoney.Text = string.Empty;
            this.txtConfirmDate.Value = string.Empty;
            this.txtAddress.Text = string.Empty;
            
        }
        /// <summary>
        /// 绑定合同信息
        /// </summary>
        /// <param name="ContractId"></param>
        private void BindContractInfoData(int ContractId)
        {
            ChinaSoft.BLL.Common.Bind bllBind = new ChinaSoft.BLL.Common.Bind();
            DataSet ds = bllBind.GetDataSet("*", "V_ContractList", "ContractId=" + ContractId);
            if (ds != null && ds.Tables.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                this.lblProjectName.Text = dr["ProjectName"].ToString();
                this.lblProjectNumber.Text = dr["ProjectNumber"].ToString();
                this.txtContractNumber.Text = dr["ContractNumber"].ToString();
                this.txtContractName.Text = dr["ContractName"].ToString();
                this.txtUnit.Text = dr["Unit"].ToString();
                this.txtContractMoney.Text = dr["ContractMoney"].ToString();
                this.txtConfirmDate.Value = Convert.ToDateTime(dr["ConfirmDate"].ToString()).ToShortDateString();
                this.txtAddress.Text = dr["Address"].ToString();
                //this.ddlType.SelectedValue = dr["ContractType"].ToString();
            }
        }
        /// <summary>
        /// 获取项目名称
        /// </summary>
        /// <param name="ProjectInfoId"></param>
        private void BindProjectNameData(int ProjectInfoId)
        {
            ChinaSoft.BLL.Common.Bind bllBind = new ChinaSoft.BLL.Common.Bind();
            DataSet ds=new DataSet();
            if (ProjectInfoId != 0)
                ds = bllBind.GetDataSet("ProjectNumber,ProjectName", "tb_MidSoft_ProjectInfo", "ProjectInfoId=" + ProjectInfoId);
            if (ds != null && ds.Tables.Count > 0)
            {
                this.lblProjectNumber.Text = ds.Tables[0].Rows[0]["ProjectNumber"].ToString();
                this.lblProjectName.Text = ds.Tables[0].Rows[0]["ProjectName"].ToString();
            }
        }


        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion

        protected void btnSave_Click(object sender, System.EventArgs e)
        {
            string strErr = "";
            if (this.txtContractNumber.Text.Trim().Length == 0)
            {
                strErr += "合同编号不能为空！\\n";
            }
            if (this.txtContractName.Text.Trim().Length == 0)
            {
                strErr += "合同名称不能为空！\\n";
            }
            if (this.txtUnit.Text.Trim().Length == 0)
            {
                strErr += "签订单位不能为空！\\n";
            }
            if (!PageValidate.IsAllNumber(txtContractMoney.Text))
            {
                strErr += "合同金额格式错误！\\n";
            }
            if (!PageValidate.IsDateTime(txtConfirmDate.Value))
            {
                strErr += "签订日期格式错误！\\n";
            }
            if (this.txtAddress.Text.Trim().Length == 0)
            {
                strErr += "地址不能为空！\\n";
            }
            if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }
            int ProjectInfoId = 0;
            if (Request.Params["ProjectId"] != null && Request.Params["ProjectId"].Trim() != "")
                ProjectInfoId = ChinaSoft.Common.Input.SetInt(Request.Params["ProjectId"]);
            string ContractNumber = this.txtContractNumber.Text;
            string ContractName = this.txtContractName.Text;
            string Unit = this.txtUnit.Text;
            decimal ContractMoney = decimal.Parse(this.txtContractMoney.Text);
            DateTime ConfirmDate = DateTime.Parse(this.txtConfirmDate.Value);
            string Address = this.txtAddress.Text;
            string FileFolder ="";
            string FileSaveName ="";
            string FileName ="";
            #region 上传文档
            if (FileUpload1.HasFile)
            {
                string result=ChinaSoft.Common.UpFile.UpDocFile(FileUpload1, Server.MapPath("/Uploads"), "", 5);
                if (result.Contains("错误"))
                {
                    Maticsoft.Common.MessageBox.Show(this, result);
                    return;
                }
                else
                {
                    FileFolder = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                    FileSaveName = result;
                    FileName = FileUpload1.FileName;
                }
            }
            #endregion
            string ContractType =  Request.Params["ContractType"];
            DateTime CreateTime = DateTime.Now;
            int CreateUserId = 0;
            if (Session["currentUserID"] != null && Session["currentUserID"].ToString() != "")
                CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
            ChinaSoft.BLL.BLL_tb_MidSoft_Contract bllContract = new ChinaSoft.BLL.BLL_tb_MidSoft_Contract();
            ChinaSoft.Model.Model_tb_MidSoft_Contract modelContract = new ChinaSoft.Model.Model_tb_MidSoft_Contract();
            if (Request.Params["ContractID"] != null && Request.Params["ContractID"].Trim() != "")
            {
                int contractId = ChinaSoft.Common.Input.SetInt(Request.Params["ContractID"]);
                modelContract = bllContract.GetModel(contractId);
                modelContract.ContractNumber = ContractNumber;
                modelContract.ContractName = ContractName;
                modelContract.Unit = Unit;
                modelContract.ContractMoney = ContractMoney;
                modelContract.ConfirmDate = ConfirmDate;
                modelContract.Address = Address;
                if (FileFolder != "")
                {
                    modelContract.FileFolder = FileFolder;
                    modelContract.FileSaveName = FileSaveName;
                    modelContract.FileName = FileName;
                }
                else if (string.IsNullOrEmpty(modelContract.FileFolder))
                {
                    modelContract.FileFolder = FileFolder;
                    modelContract.FileSaveName = FileSaveName;
                    modelContract.FileName = FileName;
                }

                modelContract.ContractType = ContractType;
                bllContract.Update(modelContract);
                #region 添加项目日志
                ChinaSoft.Model.Model_tb_Midsoft_ProjectLog modelProjectLog = new ChinaSoft.Model.Model_tb_Midsoft_ProjectLog();
                ChinaSoft.BLL.BLL_tb_Midsoft_ProjectLog bllProjectLog = new ChinaSoft.BLL.BLL_tb_Midsoft_ProjectLog();
                modelProjectLog.CreateTime = DateTime.Now;
                modelProjectLog.CreateUseId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
                string logcontent;
                if (ContractType == "0")
                    logcontent = "修改主合同“" + ContractName + "”成功！主合同编号："+ContractNumber;
                else
                    logcontent = "修改分包合同“" + ContractName + "”成功！分包合同编号："+ContractNumber;
                modelProjectLog.LogContent = logcontent;
                modelProjectLog.ProjectId = ProjectInfoId;
                bllProjectLog.Add(modelProjectLog);
                #endregion
            }
            else
            {
                #region 添加
                modelContract.ProjectInfoId = ProjectInfoId;
                modelContract.ContractNumber = ContractNumber;
                modelContract.ContractName = ContractName;
                modelContract.Unit = Unit;
                modelContract.ContractMoney = ContractMoney;
                modelContract.ConfirmDate = ConfirmDate;
                modelContract.Address = Address;
                modelContract.FileFolder = FileFolder;
                modelContract.FileSaveName = FileSaveName;
                modelContract.FileName = FileName;
                modelContract.ContractType = ContractType;
                modelContract.CreateTime = CreateTime;
                modelContract.CreateUserId = CreateUserId;

                bllContract.Add(modelContract);
                #endregion

                #region 添加项目日志
                ChinaSoft.Model.Model_tb_Midsoft_ProjectLog modelProjectLog = new ChinaSoft.Model.Model_tb_Midsoft_ProjectLog();
                ChinaSoft.BLL.BLL_tb_Midsoft_ProjectLog bllProjectLog = new ChinaSoft.BLL.BLL_tb_Midsoft_ProjectLog();
                modelProjectLog.CreateTime = DateTime.Now;
                modelProjectLog.CreateUseId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
                string logcontent;
                if (ContractType == "0")
                    logcontent = "添加主合同“" + ContractName + "”成功！主合同编号：" + ContractNumber;
                else
                    logcontent = "添加分包合同“" + ContractName + "”成功！分包合同编号：" + ContractNumber;
                modelProjectLog.LogContent =logcontent;
                modelProjectLog.ProjectId = ProjectInfoId;
                bllProjectLog.Add(modelProjectLog);
                #endregion
            }
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript'>window.location='/Contract/Add.aspx?ContractType=" + Request.Params["ContractType"] + "&ProjectId=" + ProjectInfoId + "'</script>");
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnDel_Click(object sender, ImageClickEventArgs e)
        {
            string idlist = GetSelIDlist();
           
            bll.DeleteList(idlist);
            BindData();
        }

        #region gridView
        public void BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion
            StringBuilder strWhere = new StringBuilder();
            if (Request.Params["ContractType"] != null && Request.Params["ContractType"].Trim() != "")
            {
                strWhere.AppendFormat(" and ContractType='" + Request.Params["ContractType"] + "'");
            }
            if (txtContractNumberSearch.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ContractNumber like '%{0}%'", txtContractNumberSearch.Text.Trim());
            }
            if (txtContractNameSearch.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and ContractName like '%{0}%'", txtContractNameSearch.Text.Trim());
            }
            try
            {
                //lblCount.Text = (new ChinaSoft.BLL.Common.Pager()).RecordCount("V_ContractList", strWhere.ToString()).ToString();
                ChinaSoft.BLL.Common.Pager.BindGridView(gridView, AspNetPager1, "V_ContractList", "ContractId", "*", strWhere.ToString(), "CreateTime desc", "");
            }
            catch (Exception ex)
            {
                Response.Write("数据库错误：" + ex.Message);
                Response.End();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }
        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[0].Text = "<input type=\"checkbox\" id=\"cbSelectAll\" name=\"cbSelectAll\" onclick=\"javascript:checkJs(this.checked);\" />";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                //linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")");

                //object obj1 = DataBinder.Eval(e.Row.DataItem, "Levels");
                //if ((obj1 != null) && ((obj1.ToString() != "")))
                //{
                //    e.Row.Cells[1].Text = obj1.ToString();
                //}

            }
        }
        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            if (ID.ToString().Trim().Length == 0)
                return;
            #region///获取文件路径，对文件做删除
            ChinaSoft.BLL.Common.Bind bllBind = new ChinaSoft.BLL.Common.Bind();
            DataSet ds = bllBind.GetDataSet("*", "V_ContractList", "ContractId=" + ID.ToString());
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count>0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                string strFileFloder = dr["filefolder"].ToString();
                string strFileSaveName = dr["filesavename"].ToString();
                ChinaSoft.Common.UpFile upfile = new ChinaSoft.Common.UpFile();
                try
                {
                    upfile.DeleteFile(Server.MapPath("/Uploads") + "//" + strFileFloder, strFileSaveName);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(this, ex.Message.ToString());
                }
            }
            #endregion
            ///对数据做删除
            bll.Delete(ID);
            BindData();
            //gridView.OnBind();
        }
        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("checkboxname");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }
        #endregion

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            BindData();
        }
    }
}